package com.ccsc.auth.cas.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ccsc.auth.cas.global.Constants;
import com.ccsc.auth.cas.utils.HttpUtil;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.google.common.base.Strings;

/**
 * Created by XingWen on 2017/6/22.
 */
@SuppressWarnings("serial")
public class SmsServlet extends HttpServlet implements Servlet {
    private Properties props = new Properties();

    private Producer kaptchaProducer = null;

    private String sessionKeyValue = "";

    private String sessionKeyDateValue = "";

    private String smsSender = "";

    @Override
    public void init(ServletConfig conf) throws ServletException
    {
        super.init(conf);

        Enumeration<?> initParams = conf.getInitParameterNames();
        while (initParams.hasMoreElements())
        {
            String key = (String) initParams.nextElement();
            String value = conf.getInitParameter(key);
            this.props.put(key, value);
        }

        Config config = new Config(this.props);
        this.kaptchaProducer = config.getProducerImpl();
        this.sessionKeyValue = Constants.SMS_SESSION_KEY_PREFIX.concat(config.getSessionKey());
        this.sessionKeyDateValue = Constants.SMS_SESSION_KEY_PREFIX.concat(config.getSessionDate());

        try{
            InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/smsSetting.properties");
            Properties pro = new Properties();
            pro.load(in);
            smsSender = pro.getProperty("smsSender", smsSender);
        }
        catch (Exception ex)
        {
        }
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        //获取参数
        String phoneNum = req.getParameter("phoneNum")!=null ? req.getParameter("phoneNum").trim() : "";

        if(Strings.isNullOrEmpty(phoneNum) || phoneNum.length() != 11 || !isNumeric(phoneNum)){
            return;
        }

        // create the text for the image
        String capText = this.kaptchaProducer.createText();

        // store the text in the session
        req.getSession().setAttribute(this.sessionKeyValue, capText);

        // store the date in the session so that it can be compared
        // against to make sure someone hasn't taken too long to enter
        // their kaptcha
        req.getSession().setAttribute(this.sessionKeyDateValue, new Date());
        System.out.println("短信息发送," + phoneNum + ":" + capText);
        sendSMS(phoneNum, capText);
    }

    private boolean sendSMS(String phoneNum, String capText){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("【蒙自公安】");
        stringBuffer.append("尊敬的用户，你好！您的大数据智能作战平台的4位验证码是：");
        stringBuffer.append(capText);
        stringBuffer.append("。");
        try{
            if(Strings.isNullOrEmpty(smsSender)) return false;

            StringBuffer smsStringBuffer = new StringBuffer();
            smsStringBuffer.append(smsSender);
            smsStringBuffer.append("&text=");
            smsStringBuffer.append(URLEncoder.encode(stringBuffer.toString(), "utf-8"));
            smsStringBuffer.append("&recipient=");
            smsStringBuffer.append(phoneNum);
            smsStringBuffer.append("&encoding=U");

            HttpUtil httpUtil = new HttpUtil(smsStringBuffer.toString());
            httpUtil.sendGetRequest();
            httpUtil.getResponseString();
            return true;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    private boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
}
